from rest_framework.views import exception_handler
from django.http import JsonResponse
from utils.errors import LogErrorDB
from utils.utils import responseError

def globe_exception_handler(exc, context):
    """
    全局处理DRF视图异常
    """
    request = context['request']
    
    # 处理DRF和Django的例外内置“Http404”和“PermissionDenied”
    response = exception_handler(exc, context)
    if response:
        if isinstance(response.data, list):
            msg = '; '.join(response.data)
        elif isinstance(response.data, str):
            msg = response.data
        else:
            msg = '系统内部错误'
        return JsonResponse(data=responseError(msg), status=response.status_code)

    log = LogErrorDB(request)
    log.saveDB()
    return JsonResponse(data=responseError(log.errInfo('exc_stack')), status=500)

